package com.lgd.factoryattendance.Activity.editActivity;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lgd.factoryattendance.Activity.HomePageActivity;
import com.lgd.factoryattendance.Activity.MainActivity;
import com.lgd.factoryattendance.Bean.FactoryAbnormalIssues;
import com.lgd.factoryattendance.Bean.WorkHourStatistics;
import com.lgd.factoryattendance.R;
import com.lgd.factoryattendance.Utils.ToastUtils;
import com.lgd.factoryattendance.httpService.API;
import com.lgd.factoryattendance.httpService.httpPort.IStringResponse;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class EditAssembleActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = "EditAssembleActivity";
    TextView tv_clock_type, tv_staff_name, tv_start_time, tv_end_time, tv_actual_time, tv_project_name, tv_assembly_name;
    EditText et_completion_progress, et_abnormal_time, et_problem_note;
    Spinner sp_abnormal_cause;
    Button bt_submit;
    Long edit_work_id;
    ImageView iv_refresh;
    LinearLayout layout_close;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_assemble);
        initView();
        initData();
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.bt_submit:
                String str_percent = et_completion_progress.getText().toString();
                String str_cause = sp_abnormal_cause.getSelectedItem().toString();
                String str_abnormal_time = et_abnormal_time.getText().toString();
                String str_problem = et_problem_note.getText().toString();
                if (str_percent.equals("") || str_cause.equals("请选择原因") || str_abnormal_time.equals("") ||
                        str_problem.equals("")){
                    ToastUtils.warnShowLong(getApplicationContext(),"填报内容不为空！！！");
                }else {
                    inquireDialog(str_percent,str_cause,str_abnormal_time,str_problem);
                }
                break;
            case R.id.iv_refresh:
                reStartActivity();
                break;
            case R.id.layout_close:
                finish();
                break;
            default:
                break;
        }
    }
    private void reStartActivity() {   // 刷新 当前Activity
        Intent intent = getIntent();
        overridePendingTransition(0, 0);
        intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
        finish();
        overridePendingTransition(0, 0);
        startActivity(intent);
    }
    public void initData (){
        Intent intent = getIntent();
        edit_work_id = intent.getLongExtra("editWorkId",0);
        Log.d(TAG, "initData: ----传值-----"+edit_work_id);
        if (edit_work_id == 0){
            ToastUtils.warnShowLong(getApplicationContext(),"请刷新界面！");
        }else {
            setLatestOrder(edit_work_id);
        }
    }
    // 获取 最新工单信息
    public void setLatestOrder (Long id){
        WorkHourStatistics w = new WorkHourStatistics();
        w.setWorkhourid(id);
        getLatestWorkOrder(w);
    }
    String abnormalCause_str;
    public void getLatestWorkOrder (WorkHourStatistics w){
        abnormalCause_str = null;
        API.getLatestWorkOrder(w, new IStringResponse() {
            @Override
            public void onSuccess(String result) {
                EditAssembleActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        JSONObject jsonObject = JSONObject.parseObject(result);
                        List<WorkHourStatistics> workHourList = new Gson().fromJson(jsonObject.getString("data"), new TypeToken<List<WorkHourStatistics>>(){}.getType());
                        Log.d(TAG, "----最新 工单信息-----"+workHourList);
                        if (workHourList.size() > 0){
                            tv_clock_type.setText(workHourList.get(0).getClocktype());
                            tv_staff_name.setText(workHourList.get(0).getNickName());
                            tv_start_time.setText(workHourList.get(0).getStarttime());
                            tv_end_time.setText(workHourList.get(0).getEndtime());
                            tv_actual_time.setText(workHourList.get(0).getDuration());
                            tv_project_name.setText(workHourList.get(0).getProjectName() + " ( " +
                                                workHourList.get(0).getProductAcode() + " )" );
                            tv_assembly_name.setText(workHourList.get(0).getAssemblyName());
                            et_completion_progress.setText(workHourList.get(0).getPercentage());
                            et_abnormal_time.setText(workHourList.get(0).getAbnormalWorkingHours());
                            et_problem_note.setText(workHourList.get(0).getDetails());
                            abnormalCause_str = workHourList.get(0).getRemark();
                            setAbnormalCause();  //获取 异常 信息
                        }
                    }
                });
            }
            @Override
            public void onFail(int statusCode) {}
        });
    }
    public void setAbnormalCause (){
        FactoryAbnormalIssues f = new FactoryAbnormalIssues();
        abnormalCause(f);
    }

    public List<String> abnormalCause_list = new ArrayList<>();
    // 异常 原因
    public void abnormalCause (FactoryAbnormalIssues f){
        abnormalCause_list.clear();
        API.abnormalCause(f, new IStringResponse() {
            @Override
            public void onSuccess(String result) {
                System.out.println("---异常原因----"+result);
                EditAssembleActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        JSONObject j = JSONObject.parseObject(result);
                        List<FactoryAbnormalIssues> factoryAbnormalIssuesList = new Gson().fromJson(j.getString("data"), new TypeToken<List<FactoryAbnormalIssues>>(){}.getType());
                        abnormalCause_list.add("请选择原因");
                        if (factoryAbnormalIssuesList.size() > 0 ){
                            for (FactoryAbnormalIssues f : factoryAbnormalIssuesList ) {
                                abnormalCause_list.add( f.getAbnormalissues());
                            }
                            setAbnormalSpinner(abnormalCause_list);
                        }
                    }
                });
            }
            @Override
            public void onFail(int statusCode) {}
        });
    }
    ArrayAdapter<String> cause_adapter;
    public void setAbnormalSpinner (List<String> list){
        cause_adapter = new ArrayAdapter<>(this,R.layout.spinner_item,list);
        sp_abnormal_cause.setAdapter(cause_adapter);
        int i = cause_adapter.getPosition(abnormalCause_str);
        sp_abnormal_cause.setSelection(i);  // 设置 默认值
            sp_abnormal_cause.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    String abnormal_str = list.get(position);
                    System.out.println("---异常原因:---"+abnormal_str);
                    if (abnormal_str.equals("无异常")){
                        et_abnormal_time.setText("0");
                        et_abnormal_time.setTextColor(Color.parseColor("#000000"));
                        et_abnormal_time.setEnabled(false);

                        et_problem_note.setText("无异常上报！");
                        et_problem_note.setTextColor(Color.parseColor("#000000"));
                        et_problem_note.setEnabled(false);
                    }else {
                        et_abnormal_time.setText(null);
                        et_abnormal_time.setEnabled(true);

                        et_problem_note.setText(null);
                        et_problem_note.setEnabled(true);
                    }
                }
                @Override
                public void onNothingSelected(AdapterView<?> parent) {}
            });
    }
    //    询问弹窗
    public void inquireDialog(String str_percent, String str_cause,
                              String str_abnormal_time, String str_problem){
        AlertDialog alertDialog = new AlertDialog.Builder(this)
                .setTitle(" 修 改 提 醒")
                .setMessage("确定修改这条工单信息吗？")
                .setIcon(R.drawable.tishi)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {//添加"Yes"按钮
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        WorkHourStatistics w = new WorkHourStatistics();
                        w.setWorkhourid(edit_work_id);  // 修改工单 id
                        w.setPercentage(str_percent);
                        w.setRemark(str_cause);
                        w.setAbnormalWorkingHours(str_abnormal_time);
                        w.setDetails(str_problem);
                        editWorkHour(w);
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {//添加取消
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        ToastUtils.successShowLong(getApplicationContext(),"已取消");
                    }
                })
                .create();
        alertDialog.show();
    }
    // 上报 信息
    public void editWorkHour(WorkHourStatistics w){
        API.editWorkHour(w, new IStringResponse() {
            @Override
            public void onSuccess(String result) {
                EditAssembleActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        JSONObject j = JSONObject.parseObject(result);
                        long l = Long.parseLong(j.getString("code"));
                        if (l == 200){
                            ToastUtils.successShowLong(getApplicationContext(),"修改成功！");
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    //  返回首页
                                    Intent intent = new Intent(EditAssembleActivity.this,HomePageActivity.class);
                                    setResult(Activity.RESULT_OK,intent);
                                    finish();
                                }
                            },200);
                        }
                    }
                });
            }
            @Override
            public void onFail(int statusCode) {}
        });
    }

    public void initView (){
        layout_close = findViewById(R.id.layout_close);
        layout_close.setOnClickListener(this);
        iv_refresh = findViewById(R.id.iv_refresh);
        iv_refresh.setOnClickListener(this);
        bt_submit = findViewById(R.id.bt_submit);
        bt_submit.setOnClickListener(this);
        et_problem_note = findViewById(R.id.et_problem_note);
        et_abnormal_time = findViewById(R.id.et_abnormal_time);
        int inputType = InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL;
        et_abnormal_time.setInputType(inputType);
        et_abnormal_time.setFilters(new InputFilter[]{lengthfilter});  //限制 输入
        sp_abnormal_cause = findViewById(R.id.sp_abnormal_cause);
        et_completion_progress = findViewById(R.id.et_completion_progress);
        et_completion_progress.addTextChangedListener(inputWatch(et_completion_progress)); // 限制 1~100
        tv_assembly_name = findViewById(R.id.tv_assembly_name);
        tv_project_name = findViewById(R.id.tv_project_name);
        tv_actual_time = findViewById(R.id.tv_actual_time);
        tv_end_time = findViewById(R.id.tv_end_time);
        tv_start_time = findViewById(R.id.tv_start_time);
        tv_staff_name = findViewById(R.id.tv_staff_name);
        tv_clock_type = findViewById(R.id.tv_clock_type);
    }

    //  限制 输入框输入 1~100 内数字
    public TextWatcher inputWatch(final EditText input) {
        return new TextWatcher() {
            private String outStr = ""; //这个值存储输入超过两位数时候显示的内容
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                String edit = s.toString();
                if (edit.length() ==2 && Integer.parseInt(edit)>=10){
                    outStr = edit;
                }
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String words = s.toString();
                //首先内容进行非空判断，空内容（""和null）不处理
                if (!TextUtils.isEmpty(words)) {
                    //1-100的正则验证
                    Pattern p = Pattern.compile("^(100|[1-9]\\d|\\d)$");
                    Matcher m = p.matcher(words);
                    if (m.find() || ("").equals(words)) {
                        //这个时候输入的是合法范围内的值
                    } else {
                        if (words.length() > 2) {
                            //若输入不合规，且长度超过2位，继续输入只显示之前存储的outStr
                            input.setText(outStr);
                            //重置输入框内容后默认光标位置会回到索引0的地方，要改变光标位置
                            input.setSelection(2);
                        }
                        ToastUtils.warnShowLong(EditAssembleActivity.this,"请输入范围在1-100之间的整数");
                    }
                }
            }
            @Override
            public void afterTextChanged(Editable s) {
                //这里的处理是不让输入0开头的值
                String words = s.toString();
                //首先内容进行非空判断，空内容（""和null）不处理
                if (!TextUtils.isEmpty(words)) {
                    if (Integer.parseInt(s.toString()) <= 0) {
                        input.setText("");
                        ToastUtils.warnShowLong(EditAssembleActivity.this,"请输入范围在1-100之间的整数");
                    }
                }
            }
        };
    }
    InputFilter lengthfilter = new InputFilter() {
        public CharSequence filter(CharSequence source, int start, int end,
                                   Spanned dest, int dstart, int dend) {
            // 删除等特殊字符，直接返回
            if ("".equals(source.toString())) {
                return null;
            }
            String dValue = dest.toString();
            String[] splitArray = dValue.split("\\.");
            if (splitArray.length > 1) {
                String dotValue = splitArray[1];
                int diff = dotValue.length() + 1 - 1;
                if (diff > 0) {
                    return source.subSequence(start, end - diff);
                }
            }
            return null;
        }
    };
}